<template>
  <div style="margin-top: 15px">
    <div class="tags-container">
      <div class="selected-info" v-if="localUserList.length > 0">
        已选择 {{ localUserList.length }} 人
      </div>
      <el-tag
        v-for="(tag, index) in localUserList"
        class="mx-1"
        :key="tag.id"
        closable
        @close="deleteFn(index)"
        >{{ tag.username }}</el-tag
      >
      <el-button
        class="add-button"
        type="primary"
        circle
        @click="showDialog"
      >
        <el-icon><Plus /></el-icon>
      </el-button>
    </div>
    <el-dialog
      :title="title"
      v-model="dialogCopyVisible"
      :before-close="handelcloseDialog"
      :close-on-click-modal="true"
      width="50%"
      top="60px"
      append-to-body
      center
    >
      <div class="fx-dialog" :close-on-click-modal="false">
        <div class="flex-item">
          <div class="box-left column">
            <span><i class="one" />组织架构</span>
            <el-scrollbar wrap-class="tree-wrapper-scroller orgTree1">
              <el-tree
                ref="orgTree"
                :data="treeData"
                node-key="id"
                highlight-current
                @node-click="handleNodeClick"
                v-loading="loading"
              >
                <template #default="{ data }">
                  <span class="custom-tree-node">
                    <span>
                      <i
                        v-if="data.id === 0"
                        class="treeIcon1 treeIcon_father2"
                      />
                      <i v-else class="treeIcon1 treeIcon_children2" />
                      {{ data.name }}
                    </span>
                  </span>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
          <span class="link el-icon-arrow-right" />
          <!-- 多选 -->
          <div v-if="multiple" class="box-right column">
            <span><i class="two" />人员</span>
            <div class="search-container">
              <el-input
                v-model="filterText"
                placeholder="输入关键字筛选（支持用户名和状态）"
                class="filter-text"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <el-scrollbar>
              <div v-loading="loading" class="user-list-container">
                <template v-if="filterCheckList.length > 0">
                  <el-checkbox-group v-model="copyPeople" @change="handleCheckChange">
                    <el-checkbox
                      v-for="item in filterCheckList"
                      :key="item.id"
                      :label="item.id"
                    >
                      {{ item.username }}
                      <span v-if="item.personStatus" class="red"
                        >({{ item.personStatus }})</span
                      >
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
                <el-empty v-else description="暂无数据" />
              </div>
            </el-scrollbar>
          </div>
          <!-- 单选 -->
          <div v-else class="box-right column">
            <span><i class="two" />人员</span>
            <div class="search-container">
              <el-input
                v-model="filterText"
                placeholder="输入关键字筛选（支持用户名和状态）"
                class="filter-text"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <el-scrollbar>
              <div v-loading="loading" class="user-list-container">
                <template v-if="filterCheckList.length > 0">
                  <el-radio-group v-model="copyPeople1" @change="handleCheckChange1">
                    <el-radio
                      v-for="item in filterCheckList"
                      :key="item.id"
                      :label="item.id"
                    >
                      {{ item.username }}
                      <span v-if="item.personStatus" class="red"
                        >({{ item.personStatus }})</span
                      >
                    </el-radio>
                  </el-radio-group>
                </template>
                <el-empty v-else description="暂无数据" />
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="sure">确 定</el-button>
          <el-button type="danger" plain @click="handelcloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup name="OrgPicker">
/* 组织结构下人员选择的弹框 */
// import { getListData } from '@/utils/utils';
//import mockApi from "../../api/mockApi.js";
import { findOrgData,findUserByOrgId } from "../../api/index.js"
import { mapGetters } from "vuex";
import { Search } from '@element-plus/icons-vue'

import {
  reactive,
  ref,
  createApp,
  computed,
  onMounted,
  toRefs,
  watch,
  getCurrentInstance,
  nextTick,
} from "vue";
import { useStore } from "vuex";
/* 组件局部注册 */
const app = createApp({});
const store = useStore();
const { currentInstance, proxy } = getCurrentInstance();

const emit = defineEmits(["closeDialogCopy", "copyData"]);

const props = defineProps({
  title: {
    type: String,
    default: "指定成员",
  },
  multiple: {
    default: true,
    type: Boolean,
  },
  userList: {
    default: () => {
      return [];
    },
    type: Array,
  },
  maxSelect: {
    type: Number,
    default: 0,
  },
});

const { title, multiple, userList } =
  toRefs(props);

const tableMaxHeight = ref("auto");
const treeData = ref([]);
// 单选人员
const copyPeople1 = ref("");
// 多选的人员
const copyPeople = ref([]);
// 根据组织获取的人员数组
const checkList = ref([]);

// 过滤文字
const filterText = ref("");

const perList = ref([])

const dialogCopyVisible = ref(false);

const orgTree = ref(null);

const localUserList = ref([]);

// 监听 props.userList 的变化
watch(
  () => props.userList,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      localUserList.value = [...newVal];
      if (multiple.value) {
        copyPeople.value = newVal.map(item => item.id);
      } else {
        copyPeople1.value = newVal[0].id;
      }
    }
  },
  { immediate: true }
);

const filterCheckList = computed(() => {
  // 人员列表姓名和状态模糊过滤
  if (!filterText.value) {
    return checkList.value;
  }
  const searchText = filterText.value.toLowerCase();
  return checkList.value.filter(
    (item) => 
      item.username.toLowerCase().includes(searchText) || 
      (item.personStatus && item.personStatus.toLowerCase().includes(searchText))
  );
});

// 添加加载状态
const loading = ref(false);

// 修改 getData 函数
const getData = async () => {
  try {
    loading.value = true;
    const res = await findOrgData();
    if (res.status === 0) {
      treeData.value = res.data;
      await nextTick();
      orgTree.value.setCurrentKey(0);
      const userRes = await findUserByOrgId({id:'0'});
      checkList.value = userRes.data;
    }
  } catch (error) {
    console.error('获取组织数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 修改 initState 函数
const initState = () => {
  filterText.value = "";
  // 初始化选中状态
  if (multiple.value) {
    copyPeople.value = props.userList.map(item => item.id);
    localUserList.value = [...props.userList];
  } else if (props.userList.length > 0) {
    copyPeople1.value = props.userList[0].id;
    localUserList.value = [props.userList[0]];
  }
};

// 修改 showDialog 函数
const showDialog = () => {
  dialogCopyVisible.value = true;
  // 先获取组织树数据
  getData();
  // 然后初始化状态
  nextTick(() => {
    initState();
  });
};

// 修改 handleNodeClick 函数
const handleNodeClick = async (data) => {
  try {
    loading.value = true;
    const res = await findUserByOrgId({id:data.id});
    checkList.value = res.data;
  } catch (error) {
    console.error('获取用户数据失败:', error);
  } finally {
    loading.value = false;
  }
};
// 人员对象数组进行过滤，去重！
const personSortFn = (arr) => {
  // 使用 Map 进行去重，以 id 为 key
  const uniqueMap = new Map();
  arr.forEach(item => {
    if (!uniqueMap.has(item.id)) {
      uniqueMap.set(item.id, item);
    }
  });
  return Array.from(uniqueMap.values());
};
// 修改 handleCheckChange 函数
const handleCheckChange = (val) => {
  if (!val || val.length === 0) {
    // 如果当前页面没有选中项，清空当前页面的所有选中项
    const currentPageIds = checkList.value.map(item => item.id);
    localUserList.value = localUserList.value.filter(item => !currentPageIds.includes(item.id));
  } else {
    // 获取当前页面选中的用户
    const selectedUsers = checkList.value.filter(item => val.includes(item.id));
    // 获取当前页面未选中的用户ID
    const unselectedIds = checkList.value
      .filter(item => !val.includes(item.id))
      .map(item => item.id);
    
    // 更新 localUserList，保留不在当前页面的已选用户
    localUserList.value = [
      ...localUserList.value.filter(item => !unselectedIds.includes(item.id)),
      ...selectedUsers
    ];
  }
  
  // 去重
  localUserList.value = personSortFn(localUserList.value);
  // 更新 copyPeople
  copyPeople.value = localUserList.value.map(item => item.id);
};
// 修改 handleCheckChange1 函数
const handleCheckChange1 = (val) => {
  if (!val) {
    localUserList.value = [];
    copyPeople1.value = "";
    return;
  }
  const selectedUser = checkList.value.find(item => item.id === val);
  if (selectedUser) {
    localUserList.value = [selectedUser];
    copyPeople1.value = selectedUser.id;
  }
};
// 删除表格某个数据
const deleteFn = (index) => {
  if (multiple.value) {
    const deletedId = localUserList.value[index].id;
    localUserList.value = localUserList.value.filter(item => item.id !== deletedId);
    copyPeople.value = copyPeople.value.filter(id => id !== deletedId);
    emit("copyData", localUserList.value);
  } else {
    localUserList.value = [];
    copyPeople1.value = "";
    emit("copyData", null);
  }
};
// 确认
const sure = () => {
  if (!multiple.value) {
    emit("copyData", localUserList.value[0] || null);
  } else {
    const finalData = personSortFn(localUserList.value);
    emit("copyData", finalData);
  }
  dialogCopyVisible.value = false;
};
// 取消
const handelcloseDialog = () => {
  dialogCopyVisible.value = false;
};

// 修改 watch
watch(
  dialogCopyVisible,
  (newValue) => {
    if (newValue) {
      // 先获取组织树数据
      getData();
      // 然后初始化状态
      nextTick(() => {
        initState();
      });
    }
  }
);

// 添加选择人数提示
const selectionInfo = computed(() => {
  if (props.maxSelect > 0) {
    return `已选择 ${localUserList.value.length}/${props.maxSelect} 人`;
  }
  return `已选择 ${localUserList.value.length} 人`;
});

// 修改 watch
watch(
  () => props.tableData,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      localUserList.value = [...newVal];
      if (multiple.value) {
        copyPeople.value = newVal.map(item => item.id);
      } else {
        copyPeople1.value = newVal[0].id;
      }
    }
  },
  { immediate: true }
);
</script>
<style scoped lang="scss">
.dialog-footer {
  text-align: center;
  padding: 20px 0;
}

.fx-dialog {
  .flex-item {
    display: flex;
    gap: 20px;
    min-height: 400px;

    span.link {
      width: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      font-size: 18px;
    }

    .column {
      flex: 1;
      border: 1px solid #ebeef5;
      border-radius: 8px;
      background: #fff;
      overflow: hidden;
      min-width: 280px;
      height: 400px;
      display: flex;
      flex-direction: column;

      > span {
        padding: 12px 16px;
        color: #303133;
        font-weight: 500;
        border-bottom: 1px solid #ebeef5;
        background: #f8f9fa;
        display: flex;
        align-items: center;

        i {
          margin-right: 8px;
          width: 16px;
          height: 16px;

          &.one {
            background: url("../assets/next-task.png") center/contain no-repeat;
          }

          &.two {
            background: url("../assets/next-user.png") center/contain no-repeat;
          }
        }
      }

      .el-tree {
        padding: 12px;
        flex: 1;
        overflow: auto;

        .el-tree-node__content {
          height: 36px;
          border-radius: 4px;
          transition: all 0.3s;

          &:hover {
            background-color: var(--el-color-primary-light-9);
          }

          &.is-current {
            background-color: var(--el-color-primary-light-9);
            color: var(--el-color-primary);
          }
        }
      }

      .filter-text {
        margin: 12px;
      }

      .el-checkbox-group,
      .el-radio-group {
        padding: 12px;
        flex: 1;
        overflow: auto;
      }

      .el-checkbox-group {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .el-checkbox {
          margin: 0;
          padding: 8px 12px;
          border-radius: 4px;
          transition: all 0.3s;

          &:hover {
            background-color: var(--el-color-primary-light-9);
          }

          &.is-checked {
            background-color: var(--el-color-primary-light-9);
          }
        }
      }

      .el-radio-group {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .el-radio {
          margin: 0;
          padding: 8px 12px;
          border-radius: 4px;
          transition: all 0.3s;

          &:hover {
            background-color: var(--el-color-primary-light-9);
          }

          &.is-checked {
            background-color: var(--el-color-primary-light-9);
          }
        }
      }
    }
  }
}

// 标签容器样式
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  width: 100%;
  
  .selected-info {
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-right: 8px;
  }
  
  .el-tag {
    margin: 0;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }
  
  .add-button {
    width: 32px;
    height: 32px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    margin: 0;
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      background: var(--el-color-primary-light-3);
      border-color: var(--el-color-primary-light-3);
    }
    
    &:active {
      transform: translateY(0);
      box-shadow: none;
    }
    
    .el-icon {
      font-size: 16px;
      transition: transform 0.3s;
    }
    
    &:hover .el-icon {
      transform: rotate(90deg);
    }
  }
}

// 滚动条美化
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;

  &:hover {
    background: #c0c4cc;
  }
}

::-webkit-scrollbar-track {
  background: transparent;
}

// 响应式处理
@media screen and (max-width: 768px) {
  .fx-dialog .flex-item {
    flex-direction: column;
    gap: 12px;

    .column {
      width: 100%;
      height: 300px;
    }

    span.link {
      display: none;
    }
  }
}

.search-container {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  
  .selection-limit {
    margin-top: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}

.text-selector {
  color: var(--el-color-primary);
  cursor: pointer;
  font-size: 14px;
  
  &:hover {
    text-decoration: underline;
  }
}
</style>